package com.freud.logic.business.service;

import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.freud.framework.base.BaseService;
import com.freud.framework.util.DateUtil;
import com.freud.logic.business.bean.District;
import com.freud.logic.business.bean.Good;
import com.freud.logic.business.bean.Repository;
import com.freud.logic.business.mapper.DistrictMapper;
import com.freud.logic.business.mapper.GoodMapper;
import com.freud.logic.business.mapper.RepositoryMapper;
import com.freud.logic.business.model.GoodCondition;

@Service
@Transactional
public class GoodService extends BaseService {

	@Autowired
	private GoodMapper goodMapper;

	@Autowired
	private RepositoryMapper repositoryMapper;

	@Autowired
	private DistrictMapper districtMapper;

	public List<Good> getAll(RowBounds rb, GoodCondition condition) {

		final List<Good> goods = goodMapper.getAll(rb, getStringCondition(condition.getName()),
				getIntegerCondition(condition.getRepositoryId()));
		for (final Good good : goods) {
			this.convert(good);
		}
		return goods;
	}

	public Good getById(int id) {
		return this.convert(goodMapper.get(id));
	}

	public void insert(Good good) {
		good.setOperateDate(DateUtil.currentTimestamp());
		goodMapper.insert(good);
	}

	public void update(Good good) {
		Good exist = goodMapper.get(good.getId());
		exist.setName(good.getName());
		exist.setRepositoryId(good.getRepositoryId());
		exist.setAddress(good.getAddress());
		exist.setDescription(good.getDescription());
		exist.setDistrictId(good.getDistrictId());
		exist.setOperateDate(DateUtil.currentTimestamp());
		goodMapper.update(exist);
	}

	public void delete(Integer id, Integer repositoryId) {
		goodMapper.delete(id, repositoryId);
	}

	public Good convert(final Good good) {
		District district = districtMapper.getById(good.getDistrictId());
		good.setDistrict(district == null ? new District() : district);

		Repository repository = repositoryMapper.get(good.getRepositoryId());
		if (repository != null) {
			good.setRepository(repository == null ? new Repository() : repository);
		} else {
			good.setRepository(new Repository());
		}
		return good;
	}
}
